<template>
  <footer id="footer" class="bg-gray-900 text-gray-300 bg-cover bg-center bg-no-repeat" style="background-color: #0f1011;">
    <div class="pt-12">
      <div class="max-w-8xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">


          <div class="col-span-2" >
            <img src="/images/logofooter@2x.png" alt="" style="width: 60%;margin-top: 50px;margin-left: 50px;">
          </div>
          <!-- 快速链接 -->
          <div class="col-span-1">
            <div class="mb-0">
              <h4 class="text-white text-lg font-semibold mb-5">Quick Links</h4>
              <div class="pt-2">
                <article 
                  v-for="link in quickLinks" 
                  :key="link.id" 
                  class="pb-0 mb-2"
                >
                  <div class="overflow-hidden">
                    <p class="m-0">
                      <!-- 内部链接使用 NuxtLink -->
                      <NuxtLink 
                        v-if="!link.isExternal"
                        :to="link.linkUrl" 
                        class="text-gray-400 hover:text-white no-underline"
                      >
                        {{ link.title }}
                      </NuxtLink>
                      <!-- 外部链接使用 a 标签 -->
                      <a 
                        v-else
                        :href="link.linkUrl"
                        target="_blank"
                        rel="noopener noreferrer"
                        class="text-gray-400 hover:text-white no-underline"
                      >
                        {{ link.title }}
                      </a>
                    </p>
                  </div>
                </article>
              </div>
            </div>
          </div>

          <!-- 行业新闻 -->
          <!-- <div class="col-span-1">
            <div class="mb-0">
              <h4 class="text-white text-lg font-semibold mb-5">News</h4>
              <div class="pt-2">
                <article v-for="news in newsList" :key="news.id" class="pb-0 mb-2">
                  <div class="overflow-hidden">
                    <p class="m-0">
                      <NuxtLink :to="`/article/${news.id}`" class="block max-w-full truncate text-gray-400 hover:text-white no-underline" :title="news.title">{{ news.title }}</NuxtLink>
                    </p>
                  </div>
                </article>
              </div>
            </div>
          </div> -->

          <!-- 专家动态 -->
          <!-- <div class="col-span-1">
            <div class="mb-0">
              <h4 class="text-white text-lg font-semibold mb-5">Expert updates</h4>
              <div class="pt-2">
                <article v-for="item in expertList" :key="item.id" class="pb-0 mb-2">
                  <div class="overflow-hidden">
                    <p class="m-0">
                      <NuxtLink :to="`/article/${item.id}`" class="block max-w-full truncate text-gray-400 hover:text-white no-underline" :title="item.title">{{ item.title }}</NuxtLink>
                    </p>
                  </div>
                </article>
              </div>
            </div>
          </div> -->

          <!-- 联系我们 -->
          <div class="col-span-1">
            <div class="mb-0">
              <h4 class="text-white text-lg font-semibold mb-5">Contact Us</h4>
              <div class="contact-info">
                <ul class="space-y-4">
                  <li class="flex items-start space-x-3 pb-0 mb-2">
                
                    <div>
                      <a :href="`tel:${contactInfo.tel}`" class="text-gray-400 hover:text-white no-underline">Phone：{{ contactInfo.tel }}</a>
                      <!-- <span class="block text-sm text-gray-500">联系电话</span> -->
                    </div>
                  </li>
                  <li class="flex items-start space-x-3 pb-0 mb-2">
                  
                    <div>
                      <a :href="`mailto:${contactInfo.email}`" class="text-gray-400 hover:text-white no-underline">E-mail：{{ contactInfo.email }}</a>
                      <!-- <span class="block text-sm text-gray-500">Email</span> -->
                    </div>
                  </li>
                  <li class="flex items-start space-x-3 pb-0 mb-2 border-0">
                    <div style="width: 450px;">
                      <span class="text-gray-400 text-sm">Address：{{ contactInfo.address }}</span>
                    </div>
                  </li>
                 
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Footer Bottom -->
      <div class="border-t border-gray-700 mt-8">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div class="grid grid-cols-1 lg:grid-cols-3 gap-4 py-6">
            <div class="lg:col-span-2">
              <div class="flex flex-col space-y-2">
                <!-- <div class="text-sm text-gray-400">© Copyright 2021 by hongyuan3e.com</div> -->
                <div class="flex items-center space-x-2 text-sm">
              
                  <a href="https://beian.miit.gov.cn/" target="_blank" class="text-gray-400 hover:text-white no-underline">
                    <span>© 2023 CBAM Service platform All right reserved</span>
                  </a>
                </div>

                  
              </div>
            </div>
            <div class="lg:col-span-1">
              <!-- <div class="flex items-center space-x-3">
                <a href="http://www.beian.gov.cn/portal/registerSystemInfo" target="_blank" class="text-gray-400 hover:text-white no-underline flex items-center">
                    <img src="//img.alicdn.com/tfs/TB1..50QpXXXXX7XpXXXXXXXXXX-40-40.png" alt="" class="w-5 h-5 mr-1">
                    <span>Hunan ICP No. 2022006810-2</span>
                  </a>
              </div> -->
              <!-- <li class="flex items-start space-x-3 mb-0 pb-3 border-0">
                   <img src="/images/facebook@2x.png" alt="" style="width: 30px;height: 30px;">
                   <img src="/images/t@2x.png" alt="" style="width: 30px;height: 30px;">
                   <img src="/images/ins@2x.png" alt="" style="width: 30px;height: 30px;">
                   <img src="/images/a@2x.png" alt="" style="width: 30px;height: 30px;">

                  </li> -->
                  <li class="flex items-start space-x-3 mb-0 pb-3 border-0">
                   <div class="relative" @click="showQRCode('twitter')" @mouseenter="showQRCode('twitter')" @mouseleave="hideQRCode('twitter')">
                     <img src="/images/twitter.png" class="cursor-pointer" alt="" style="width: 30px;height: 30px;">
                     <div v-if="activeQRCode === 'twitter'" class="absolute bottom-full left-1/2  mb-2 bg-white p-2 rounded shadow-lg z-50" style="width: 250px;">
                       <img src="/images/tuitan.jpg" alt="Twitter QR Code" style="width: 220px;height: 220px;">
                     </div>
                   </div>
                   
                   <div class="relative" @click="showQRCode('weixin')" @mouseenter="showQRCode('weixin')" @mouseleave="hideQRCode('weixin')">
                     <img src="/images/weixin.png" class="cursor-pointer" alt="" style="width: 30px;height: 30px;">
                     <div v-if="activeQRCode === 'weixin'" class="absolute bottom-full left-1/2  mb-2 bg-white p-2 rounded shadow-lg z-50"  style="width: 250px;">
                      <img src="/images/weitan.png" alt="Twitter QR Code" style="width: 220px;height: 220px;">
                     
                    </div>
                   </div>
                   
                   <div class="relative" @click="showQRCode('whatsapp')" @mouseenter="showQRCode('whatsapp')" @mouseleave="hideQRCode('whatsapp')">
                     <img src="/images/whatapp2.png" class="cursor-pointer" alt="" style="width: 30px;height: 30px;">
                     <div v-if="activeQRCode === 'whatsapp'"  class="absolute bottom-full left-1/2  mb-2 bg-white p-2 rounded shadow-lg z-50" style="width: 250px;">
                      <img src="/images/wotan.png" alt="Twitter QR Code" style="width: 220px;height: 220px;">

                     </div>
                   </div>
                   
                   <div class="relative" @click="showQRCode('facebook')" @mouseenter="showQRCode('facebook')" @mouseleave="hideQRCode('facebook')">
                     <img src="/images/fackbook.png" class="cursor-pointer" alt="" style="width: 30px;height: 30px;">
                     <div v-if="activeQRCode === 'facebook'"  class="absolute bottom-full left-1/2  mb-2 bg-white p-2 rounded shadow-lg z-50" style="width: 250px;">
                      <img src="/images/ftan.png" alt="Twitter QR Code" style="width: 220px;height: 220px;">

                     </div>
                   </div>
                  </li>
            </div>
          </div>
        </div>
      </div>
    </div>
  </footer>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { articleApi, contactApi, linksApi } from '~/public/utils/api'

// 联系信息
const contactInfo = ref({
  tel: '4006790996',
  email: 'contacts@hongyuan3e.com',
  address: '北京市海淀区中关村东路80号'
})

// 新闻列表（Industry News）
const newsList = ref([])
// 专家动态（Platform Dynamics）
const expertList = ref([])

// 快速链接列表
const quickLinks = ref([])

// 默认快速链接（作为fallback）
const defaultQuickLinks = [
  {
    id: 1,
    title: 'Expert Updates',
    linkUrl: '/member/expert',
    isExternal: false
  },
  {
    id: 2,
    title: 'Expert Modeler',
    linkUrl: '/plan/E3M',
    isExternal: false
  },
  {
    id: 3,
    title: 'Corporate Carbon Accounting',
    linkUrl: '/plan/qiye',
    isExternal: false
  }
]

// 二维码显示状态
const activeQRCode = ref('')

// 显示二维码
const showQRCode = (type) => {
  activeQRCode.value = type
}

// 隐藏二维码
const hideQRCode = (type) => {
  if (activeQRCode.value === type) {
    activeQRCode.value = ''
  }
}

// 获取联系信息
const fetchContactInfo = async () => {
  try {
    const result = await contactApi.getContactInfo()
    if (result.data) {
      contactInfo.value = {
        tel: result.data.tel || contactInfo.value.tel,
        email: result.data.email || contactInfo.value.email,
        address: result.data.address || contactInfo.value.address
      }
    }
  } catch (error) {
    console.error('Failed to fetch contact info:', error)
  }
}

// 获取 Industry News（categoryId: 2）
const fetchNewsList = async () => {
  try {
    const res = await articleApi.getList({ pageSize: 5, pageNum: 1, categoryId: 2 })
    const rows = res?.rows || res?.data?.rows || []
    newsList.value = rows.map(r => ({ id: r.id || r.articleId, title: r.title || '' }))
  } catch (error) {
    console.error('Failed to fetch news list:', error)
  }
}

// 获取 Platform Dynamics（categoryId: 1）
const fetchExpertList = async () => {
  try {
    const res = await articleApi.getList({ pageSize: 5, pageNum: 1, categoryId: 1 })
    const rows = res?.rows || res?.data?.rows || []
    expertList.value = rows.map(r => ({ id: r.id || r.articleId, title: r.title || '' }))
  } catch (error) {
    console.error('Failed to fetch expert list:', error)
  }
}

// 判断是否为内部链接
const isInternalLink = (url) => {
  if (!url) return true
  if (url.startsWith('/')) return true
  
  try {
    const urlObj = new URL(url)
    // 判断是否为当前网站域名
    return urlObj.hostname === 'cbam.hongyuan3e.com' || 
           urlObj.hostname === window.location.hostname
  } catch {
    return true
  }
}

// 从完整URL中提取路径部分
const extractPath = (url) => {
  if (!url) return '/'
  
  try {
    // 如果是相对路径，直接返回
    if (url.startsWith('/')) {
      return url
    }
    
    // 如果是完整URL，提取路径部分
    const urlObj = new URL(url)
    return urlObj.pathname
  } catch (error) {
    // URL解析失败，尝试直接返回
    console.warn('Invalid URL:', url)
    return url
  }
}

// 获取快速链接列表
const fetchQuickLinks = async () => {
  try {
    const result = await linksApi.getList()
    if (result.data && Array.isArray(result.data) && result.data.length > 0) {
      // 处理链接URL，智能判断内外部链接
      quickLinks.value = result.data.map(link => {
        const url = link.linkUrl || ''
        return {
          id: link.id,
          title: link.title || '',
          linkUrl: isInternalLink(url) ? extractPath(url) : url,
          isExternal: !isInternalLink(url)
        }
      })
    } else {
      // 如果接口返回空数据，使用默认链接
      quickLinks.value = defaultQuickLinks
    }
  } catch (error) {
    console.error('Failed to fetch quick links:', error)
    // 接口调用失败，使用默认链接
    quickLinks.value = defaultQuickLinks
  }
}

onMounted(async () => {
  await Promise.all([
    fetchContactInfo(),
    fetchNewsList(),
    fetchExpertList(),
    fetchQuickLinks()
  ])
})
</script>
